package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

public class HailiziNewsAnalyse implements AnalyseNews {
	
	private static final String[] regex={
		
		"http://www.hilizi.com/html/[0-9]+/[^/]+_[0-9]+/[0-9]+.html",
		"http://.*hilizi.com/.*/[0-9]+-[0-9]+/[0-9]+/content_[0-9]+.htm",
	};	
	
	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}		
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();	
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);				
		news.setUrl(url);	
		
		title =doc.select("div.title h1").text();	
		if(StringUtils.isBlank(title)){
			title=doc.select("div#p3t1t1").text();
			if(StringUtils.isBlank(title)){
				title=doc.select("div.g2t1t1").text();
				if (title!=null)title=StringUtils.substringBefore(title, "-");
			}
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("div.content"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("td.content_content"));
		}
		date=DateUtils.matchDate(doc.select("div.title,div#p3t1t2,div.g2t1t2").text());
		author=JSoupUtils.matchAuthor(doc, "来源：");
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(content);
			news.setDate(date);	
			news.setAuthor(author);
		return news;
	}	
	
	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
	
	public static void main(String[] args) {
		String url="http://www.hilizi.com/newhealth/2013-09/22/content_542430.htm";
		HailiziNewsAnalyse analyse=new HailiziNewsAnalyse();		
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

}
